package com.example.gyj.service;

import com.example.gyj.dao.GoodsDao;
import com.example.gyj.dao.OrderDao;
import com.example.gyj.entity.OrderInfo;
import com.example.gyj.entity.SeckillOrder;
import com.example.gyj.entity.User;
import com.example.gyj.redis.OrderKey;
import com.example.gyj.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *
 * @author Gao
 * @date 2018/10/21
 */
@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private RedisService redisService;

    /**
     * 根据用户Id和商品Id获得商品秒杀订单
     *
     * @param userId
     * @param goodsId
     */
    public SeckillOrder getSeckillOrderByUserIdGoodsId(Long userId, long goodsId) {
        ///return orderDao.getSeckillOrderByUserIdAndGoodsId(userId, goodsId);
        //从缓存中取数据
        return redisService.get(OrderKey.getSeckillOrderByUidGid, "" + userId + "_" + goodsId, SeckillOrder.class);
    }

    /**
     * 根据orderId获取订单信息
     * @param orderId
     */
    public OrderInfo getOrderById(long orderId) {
        return orderDao.getOrderById(orderId);
    }

    /**
     * 下订单，写入秒杀订单
     * @param user
     * @param goods
     */
    public OrderInfo createOrder(User user, GoodsVo goods) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getSeckillPrice());
        //1在线下单
        orderInfo.setOrderChannel(1);
        //0未支付
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        //插入到订单表中
        orderDao.insertOrder(orderInfo);

        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setOrderId(orderInfo.getId());
        seckillOrder.setUserId(user.getId());
        //插入到秒杀订单表中
        orderDao.insertSeckillOrder(seckillOrder);

        //将秒杀订单放入Redis
        redisService.set(OrderKey.getSeckillOrderByUidGid, "" + user.getId() + "_" + goods.getId(), seckillOrder);
        return orderInfo;
    }

    /**
     * 删除订单和秒杀订单
     */
    public void deleteOrders() {
        orderDao.deleteOrders();
        orderDao.deleteSeckillOrders();
    }
}
